# -*- coding:utf-8 -*-
"""
@Time : 2020-12-15 10:52
@Author: langengel
@Des: 框架初始化
"""

from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError

from config import config, template
from fastapi.staticfiles import StaticFiles
from saas.response.BaseResponse import UnicornException
from saas.response.http_error import http_error_handler, unicorn_exception_handler
from saas.response.validation_error import http422_error_handler
from saas.events.events import create_stop_app_handler, create_start_app_handler
from saas.middleware.middleware import init_middlewares
from saas.router.router import router
from saas.websocket.websocket import Echo as WebSocket
from fastapi.templating import Jinja2Templates

# fastapi基础配置

application = FastAPI(title=config.PROJECT_NAME, version=config.VERSION, description=config.DESCRIPTION)


def init_app() -> FastAPI:
    """
    应用初始化
    :return: fastapi
    """
    # 添加事件
    application.add_event_handler("startup", create_start_app_handler(application))
    application.add_event_handler("shutdown", create_stop_app_handler(application))

    # 添加错误处理
    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError, http422_error_handler)
    application.add_exception_handler(UnicornException, unicorn_exception_handler)

    # 中间件
    init_middlewares(application)

    # 路由
    application.include_router(router)

    # webSocket
    application.add_websocket_route('/ws', WebSocket)

    # 挂载静态文件资源目录
    application.mount('/', StaticFiles(directory=template.STATIC_DIR), name="public")
    # 模版路径
    application.mount('/template', StaticFiles(directory=template.TEMPLATE_DIR), name="template")
    application.render = Jinja2Templates(directory=template.TEMPLATE_DIR)

    return application


app = init_app()
